package cn.huijielong.modules.app.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.huijielong.common.utils.Query;
import cn.huijielong.common.utils.RD;
import cn.huijielong.common.utils.VSUtil;
import cn.huijielong.modules.app.entity.UserEntity;
import cn.huijielong.modules.app.service.WechatService;
import cn.huijielong.modules.pub.entity.UserOpenidEntity;
import cn.huijielong.modules.pub.service.MerchantService;
import cn.huijielong.modules.pub.service.UserOpenidService;
import cn.huijielong.modules.sys.service.SysUserTokenService;

/**
 * APP测试接口
 *
 * @date 2017-03-23 15:47
 */
@RestController
@RequestMapping("/app/wx")
public class WechatController {
	@Autowired
	private WechatService wechatService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private UserOpenidService userOpenidService;
	@Autowired
	private MerchantService merchantService;
    /**
     * 获取用户信息
     */
	@PostMapping("login")
    public RD login(){
    	Query q=Query.createRequest();
    	UserEntity user=wechatService.getWxUserinfo(q.getString("code"));
    	user.setNickName(q.getString("nickName"));
    	user.setUsername(String.valueOf(VSUtil.getRandom(8)));
    	String avatarUrl=q.getString("avatarUrl");
    	user.setHeadImg(avatarUrl);
    	user=wechatService.getUserinfo(user);
    	RD r = sysUserTokenService.createToken(user.getUserId());
    	Query ui=Query.empty();
    	ui.addParam("userId", user.getUserId()).
    	addParam("openid", user.getOpenid()).
    	addParam("merchantId", user.getMerchantId()).
    	addParam("token", r.get("token"));
    	
        return RD.ok().put("userData", ui);
    }
	@PostMapping("reloadToken")
	public RD reloadToken(){
		Query q=Query.createRequest();
		q.isEmpty("openid", "openid不能为空");
		String openid=q.getString("openid");
		UserOpenidEntity uoe=userOpenidService.queryByOpenid(openid);
		RD r = sysUserTokenService.createToken(uoe.getUserId());
		Long merchantId=merchantService.querySelectedMerchantId(uoe.getUserId());
		
		Query ui=Query.empty();
		ui.addParam("userId", uoe.getUserId()).
		addParam("openid", uoe.getOpenid()).
		addParam("merchantId", merchantId).
		addParam("token", r.get("token"));
		
		return RD.ok().put("userData", ui);
	}


}
